import DigitalHuman3D from "../../components/DigitalHuman3D/DigitalHuman3D";
import Video from "../../components/Video/index";
import Chat from "../../components/Chat/index";
import React, { useState, useEffect, useRef } from "react";
import styles from "./index.module.scss";
import { Button } from "antd";
import { useNavigate } from "react-router-dom";

// 导入所有需要的图片资源
import bgDay from "../../assets/bg-day.png";
import indexLightBackground from "../../assets/indexLightBackground.png";
import borderDay from "../../assets/border-day.png";
import border from "../../assets/border.png";
import ceilDay from "../../assets/ceil-day.png";
import ceil from "../../assets/ceil.png";
import floorDay from "../../assets/floor-day.png";
import floor from "../../assets/floor.png";
import nightModel from "../../assets/night-model.svg";
import dayModel from "../../assets/day-model.svg";
import answerModel from "../../assets/answer-model.svg";
import answerIcon from "../../assets/answer-icon.svg";
import chatModelActive from "../../assets/chat-model-active.svg";
import chatModel from "../../assets/chat-model.svg";
import speaking from "../../assets/speaking.jpeg";
import speeching from "../../assets/speeching.gif";

const IndexTow: React.FC = () => {
  const [isLightTheme, setIsLightTheme] = useState(true);
  const [currentMode, setCurrentMode] = useState<'answer' | 'chat'>('answer');
  const [answerIconState, setAnswerIconState] = useState('answer-model.svg');
  const [isRecording, setIsRecording] = useState(false); // 语音识别状态
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const [recognition, setRecognition] = useState<any>(null); // 语音识别对象
  const [recognitionError, setRecognitionError] = useState<string>(''); // 语音识别错误信息
  const [speechResult, setSpeechResult] = useState<string>(''); // 语音识别结果
  const [isStarting, setIsStarting] = useState(false); // 防止重复启动
  const [retryCount, setRetryCount] = useState(0); // 重试次数
  const chatInputRef = useRef<HTMLTextAreaElement>(null); // Chat组件输入框的ref
  const nav = useNavigate();
  
  // 添加CSS动画样式
  const pulseAnimation = `
    @keyframes pulse {
      0% { transform: scale(1); }
      50% { transform: scale(1.1); }
      100% { transform: scale(1); }
    }
    
    @keyframes blink {
      0%, 50% { opacity: 1; }
      51%, 100% { opacity: 0.5; }
    }
  `;

  // 注入CSS动画
  useEffect(() => {
    const styleElement = document.createElement('style');
    styleElement.textContent = pulseAnimation;
    document.head.appendChild(styleElement);
    
    return () => {
      document.head.removeChild(styleElement);
    };
  }, []);



  // 初始化语音识别
  useEffect(() => {
    const initSpeechRecognition = () => {
      console.log('初始化语音识别...');
      
      // 使用更安全的类型检查
      const SpeechRecognition = 
        (window as any).SpeechRecognition || 
        (window as any).webkitSpeechRecognition;
      
      if (SpeechRecognition) {
        try {
          const recognition = new SpeechRecognition();
          console.log('语音识别对象创建成功');
          
          recognition.continuous = false;
          recognition.interimResults = true;
          recognition.lang = 'zh-CN';
          
          console.log('语音识别配置完成:', {
            continuous: recognition.continuous,
            interimResults: recognition.interimResults,
            lang: recognition.lang
          });
          
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          recognition.onresult = (event: any) => {
            console.log('语音识别结果事件:', event);
            
            let finalTranscript = '';
            let interimTranscript = '';
            
            for (let i = event.resultIndex; i < event.results.length; i++) {
              const transcript = event.results[i][0].transcript;
              if (event.results[i].isFinal) {
                finalTranscript += transcript;
              } else {
                interimTranscript += transcript;
              }
            }
            
            console.log('最终结果:', finalTranscript);
            console.log('临时结果:', interimTranscript);
            
            if (finalTranscript) {
              // 将识别的文字发送到Chat组件
              handleSpeechResult(finalTranscript);
              setIsRecording(false);
            }
          };
          
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          recognition.onerror = (event: any) => {
            console.error('语音识别错误:', event.error);
            setIsRecording(false);
            setIsStarting(false);
            
            // 根据错误类型给出不同提示
            let errorMessage = '';
            switch (event.error) {
              case 'network':
                errorMessage = '网络连接问题，请检查网络后重试';
                console.warn(errorMessage);
                // 网络错误时，尝试重新初始化（最多重试3次）
                if (retryCount < 3) {
                  setRetryCount(retryCount + 1);
                  setTimeout(() => {
                    console.log(`尝试重新初始化语音识别... (第${retryCount + 1}次重试)`);
                    initSpeechRecognition();
                  }, 2000);
                } else {
                  console.warn('语音识别重试次数已达上限，请刷新页面重试');
                  setRetryCount(0);
                }
                break;
              case 'not-allowed':
                errorMessage = '麦克风权限被拒绝，请允许麦克风访问';
                console.warn(errorMessage);
                break;
              case 'no-speech':
                errorMessage = '未检测到语音，请说话';
                console.warn(errorMessage);
                break;
              case 'aborted':
                errorMessage = '语音识别被中断';
                console.warn(errorMessage);
                break;
              case 'audio-capture':
                errorMessage = '无法捕获音频，请检查麦克风';
                console.warn(errorMessage);
                break;
              case 'service-not-allowed':
                errorMessage = '语音识别服务不可用，请稍后重试';
                console.warn(errorMessage);
                break;
              default:
                errorMessage = '语音识别出现未知错误';
                console.warn(errorMessage);
            }
            setRecognitionError(errorMessage);
            
            // 5秒后清除错误信息
            setTimeout(() => {
              setRecognitionError('');
            }, 5000);
          };
          
          recognition.onend = () => {
            console.log('语音识别结束');
            setIsRecording(false);
            setIsStarting(false);
          };
          
          recognition.onstart = () => {
            console.log('语音识别开始');
            setIsRecording(true);
            setIsStarting(false);
          };
          
          // 添加更多事件处理
          recognition.onnomatch = () => {
            console.log('语音识别无匹配结果');
            setIsRecording(false);
            setIsStarting(false);
          };
          
          recognition.onsoundstart = () => {
            console.log('检测到声音');
          };
          
          recognition.onsoundend = () => {
            console.log('声音结束');
          };
          
          recognition.onspeechstart = () => {
            console.log('开始说话');
          };
          
          recognition.onspeechend = () => {
            console.log('说话结束');
          };
          
          setRecognition(recognition);
          console.log('语音识别初始化成功');
        } catch (error) {
          console.error('创建语音识别对象失败:', error);
          setRecognitionError('语音识别初始化失败，请检查浏览器支持');
        }
      } else {
        console.warn('浏览器不支持语音识别，请使用Chrome或Edge浏览器');
        setRecognitionError('浏览器不支持语音识别');
      }
    };
    
    initSpeechRecognition();
    
    // 清理函数
    return () => {
      if (recognition) {
        try {
          recognition.stop();
        } catch (error) {
          console.log('清理语音识别时出错:', error);
        }
      }
    };
  }, []);

  // 添加网络状态监听
  useEffect(() => {
    const handleOnline = () => {
      console.log('网络连接已恢复');
      setRecognitionError('');
    };
    
    const handleOffline = () => {
      console.log('网络连接已断开');
      setRecognitionError('网络连接已断开，请检查网络');
    };
    
    window.addEventListener('online', handleOnline);
    window.addEventListener('offline', handleOffline);
    
    return () => {
      window.removeEventListener('online', handleOnline);
      window.removeEventListener('offline', handleOffline);
    };
  }, []);

  // 处理语音识别结果
  const handleSpeechResult = (transcript: string) => {
    console.log('处理语音识别结果:', transcript);
    
    if (!transcript || transcript.trim() === '') {
      console.warn('语音识别结果为空');
      return;
    }
    
    // 设置语音识别结果状态
    setSpeechResult(transcript);
    
    // 直接设置Chat组件的输入值
    if (chatInputRef.current) {
      console.log('设置Chat组件输入值:', transcript);
      chatInputRef.current.value = transcript;
      
      // 触发input事件
      const inputEvent = new Event('input', { bubbles: true });
      chatInputRef.current.dispatchEvent(inputEvent);
      
      // 同时触发change事件
      const changeEvent = new Event('change', { bubbles: true });
      chatInputRef.current.dispatchEvent(changeEvent);
      
      console.log('语音识别结果已填入输入框:', transcript);
    } else {
      console.warn('Chat组件输入框未找到');
    }
  };

  // 检查语音识别状态
  const checkRecognitionState = () => {
    if (!recognition) {
      console.warn('语音识别未初始化');
      return false;
    }
    return true;
  };

  // 检查网络连接
  const checkNetworkConnection = () => {
    if (!navigator.onLine) {
      console.warn('网络连接已断开');
      setRecognitionError('网络连接已断开，请检查网络');
      return false;
    }
    return true;
  };



  // 开始语音识别
  const startSpeechRecognition = () => {
    console.log('点击语音识别按钮');
    
    if (!checkRecognitionState() || currentMode !== 'chat') {
      console.log('语音识别条件不满足:', { 
        hasRecognition: !!recognition, 
        currentMode, 
        isRecording,
        isStarting
      });
      return;
    }
    
    // 检查网络连接
    if (!checkNetworkConnection()) {
      return;
    }
    
    if (isRecording) {
      // 如果正在录音，则停止录音
      try {
        console.log('尝试停止语音识别...');
        recognition!.stop();
        // 立即设置状态为false，不等待onend事件
        setIsRecording(false);
        console.log('录音已停止');
      } catch (error) {
        console.error('停止语音识别失败:', error);
        setIsRecording(false); // 确保状态重置
        setRecognitionError('停止录音失败，请重试');
      }
    } else {
      // 如果未在录音，则开始录音
      if (isStarting) {
        console.log('语音识别正在启动中，请稍候...');
        return;
      }
      
      try {
        // 先清除之前的错误信息
        setRecognitionError('');
        setIsStarting(true);
        console.log('尝试开始语音识别...');
        
        // 确保recognition对象存在且未在运行
        if (recognition) {
          // 先尝试停止，以防之前的状态未正确清理
          try {
            recognition.stop();
          } catch {
            // 忽略停止错误
          }
          
          // 等待一小段时间再开始
          setTimeout(() => {
            try {
              console.log('开始启动语音识别...');
              recognition.start();
              console.log('语音识别启动命令已发送');
            } catch (startError) {
              console.error('启动语音识别失败:', startError);
              setIsRecording(false);
              setIsStarting(false);
              setRecognitionError('启动语音识别失败，请重试');
            }
          }, 200);
        }
      } catch (error) {
        console.error('启动语音识别失败:', error);
        setIsRecording(false);
        setIsStarting(false);
        setRecognitionError('启动语音识别失败，请重试');
      }
    }
  };

  useEffect(() => {
    const checkTheme = () => {
      const localThemeMode = localStorage.getItem('themeMode') || 'system';
      let currentTheme = localThemeMode;
      
      // 如果设置为跟随系统，则检测系统主题
      if (localThemeMode === 'system') {
        currentTheme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
      }
      
      const bodyTheme = document.body.dataset.theme || 
                       (document.body.classList.contains('dark') ? 'dark' : 'light');
      const finalTheme = currentTheme || bodyTheme;
      setIsLightTheme(finalTheme === 'light');
    };

    checkTheme();

    const observer = new MutationObserver(checkTheme);
    observer.observe(document.body, { 
      attributes: true, 
      attributeFilter: ['data-theme', 'class'] 
    });

    const handleStorageChange = () => {
      checkTheme();
    };
    window.addEventListener('storage', handleStorageChange);
    
    // 监听系统主题变化
    const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
    const handleSystemThemeChange = () => {
      const localThemeMode = localStorage.getItem('themeMode') || 'system';
      if (localThemeMode === 'system') {
        checkTheme();
      }
    };
    mediaQuery.addEventListener('change', handleSystemThemeChange);

    return () => {
      observer.disconnect();
      window.removeEventListener('storage', handleStorageChange);
      mediaQuery.removeEventListener('change', handleSystemThemeChange);
    };
  }, []);

    const toggleTheme = () => {
    const newTheme = !isLightTheme;
    setIsLightTheme(newTheme);
    
    // 获取当前主题模式
    const currentThemeMode = localStorage.getItem('themeMode') || 'system';
    
    // 如果当前是跟随系统，则切换到固定模式
    if (currentThemeMode === 'system') {
      const systemTheme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
      const newThemeMode = systemTheme === 'dark' ? 'light' : 'dark';
      localStorage.setItem('themeMode', newThemeMode);
    } else {
      // 如果当前是固定模式，则切换到跟随系统
      localStorage.setItem('themeMode', 'system');
    }
    
    const themeMode = newTheme ? 'light' : 'dark';
    document.body.dataset.theme = themeMode;
    document.body.classList.toggle('dark', themeMode === 'dark');
  };

  const switchToAnswerMode = () => {
    setCurrentMode('answer');
    setAnswerIconState('answer-icon.svg');
  };

  const switchToChatMode = () => {
    setCurrentMode('chat');
    setAnswerIconState('answer-model.svg');
  };
  const boxStyle = {
    backgroundImage: isLightTheme 
      ? `url(${bgDay})` 
      : `url(${indexLightBackground})`,
    backgroundSize: '100% 100%',
    height: '100vh',
    width: '100vw'
  };

  const row2Style = {
    backgroundImage: isLightTheme 
      ? `url(${borderDay})` 
      : `url(${border})`,
    backgroundSize: '100% 100%',
    width: '700px',
    height: '520px',
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
    marginLeft: '120px',
    position: 'relative' as const
  };

  const headerStyle = {
    backgroundImage: isLightTheme 
      ? `url(${ceilDay})` 
      : `url(${ceil})`,
    backgroundSize: '100% 100%',
    height: '70px',
    marginBottom: '30px',
    position: 'relative' as const
  };

  const footerStyle = {
    backgroundImage: isLightTheme 
      ? `url(${floorDay})` 
      : `url(${floor})`,
    backgroundSize: '100% 100%',
    height: '70px',
    marginTop: '101px'
  };
  const topStyle={
    position: 'absolute' as const,
    top: '10px',
    right: '50px',
    display: 'flex',
    alignItems: 'center',
    gap: '15px'
  }
  return (
    <div style={boxStyle}>
      <div style={headerStyle}>
        <div style={topStyle}>
          <Button 
            onClick={toggleTheme} 
            style={{ 
              background: 'transparent', 
              border: 'none', 
              padding: '8px',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              width: '50px',
              height: '50px'
            }}
          >
            <img 
              src={isLightTheme ? nightModel : dayModel} 
              alt="切换主题"
              style={{ width: '50px', height: '50px' }}
            />
          </Button>
          <Button onClick={()=>nav('/')}>返回主页</Button>
        </div>
      </div>
              <div className={styles.main}>
        <div className={styles.row1}>
          <DigitalHuman3D height={370} />
        </div>
        <div style={row2Style}>
          {currentMode === 'answer' ? <Video /> : <Chat inputRef={chatInputRef} speechResult={speechResult} />}
          
          {/* 添加speaking.jpeg图片 - 只在Chat模式下显示 */}
          {currentMode === 'chat' && (
            <div style={{
              position: 'absolute',
              bottom: '-100px',
              right: '40%',
              transform: 'translate(-50%, -50%)',
              zIndex: 10,
              pointerEvents: 'auto', // 允许点击交互
              transition: 'all 0.3s ease',
              cursor: 'pointer'
            }}
            onClick={startSpeechRecognition}
            title={isRecording ? '再次点击停止录音' : '点击开始语音识别'}
            >
              <img 
                src={isRecording || isStarting ? speeching : speaking}
                alt={isRecording ? "正在录音" : (isStarting ? "启动中" : "语音识别")}
                style={{
                  width: '60px',
                  height: '60px',
                  objectFit: 'cover',
                  borderRadius: '50%',
                  boxShadow: isLightTheme 
                    ? '0 4px 20px rgba(0, 0, 0, 0.2)' 
                    : '0 4px 20px rgba(255, 255, 255, 0.1)',
                  border: isRecording 
                    ? '3px solid #ff4d4f' 
                    : (isStarting 
                        ? '3px solid #faad14'
                        : (isLightTheme 
                            ? '3px solid rgba(255, 255, 255, 0.9)' 
                            : '3px solid rgba(255, 255, 255, 0.3)')),
                  transition: 'all 0.3s ease',
                  animation: isRecording || isStarting ? 'pulse 1.5s infinite, blink 1s infinite' : 'none'
                }}
              />
              {/* 提示信息 */}
              <div style={{
                position: 'absolute',
                bottom: '-25px',
                left: '50%',
                transform: 'translateX(-50%)',
                fontSize: '10px',
                color: isRecording ? '#ff4d4f' : (isLightTheme ? '#666' : '#ccc'),
                textAlign: 'center',
                whiteSpace: 'nowrap',
                fontWeight: isRecording ? 'bold' : 'normal'
              }}>
                {isStarting ? '启动中...' : (isRecording ? '点击停止' : '语音识别')}
              </div>
              
              {/* 录音状态指示器 */}
              {(isRecording || isStarting) && (
                <div style={{
                  position: 'absolute',
                  top: '-10px',
                  right: '-10px',
                  width: '20px',
                  height: '20px',
                  borderRadius: '50%',
                  backgroundColor: isRecording ? '#ff4d4f' : '#faad14',
                  border: '2px solid white',
                  animation: 'blink 1s infinite',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  fontSize: '8px',
                  color: 'white',
                  fontWeight: 'bold'
                }}>
                  {isStarting ? '⏳' : '●'}
                </div>
              )}
              
              {/* 错误信息提示 */}
              {recognitionError && (
                <div style={{
                  position: 'absolute',
                  top: '-40px',
                  left: '50%',
                  transform: 'translateX(-50%)',
                  backgroundColor: '#ff4d4f',
                  color: 'white',
                  padding: '4px 8px',
                  borderRadius: '4px',
                  fontSize: '10px',
                  whiteSpace: 'nowrap',
                  zIndex: 20,
                  boxShadow: '0 2px 8px rgba(0, 0, 0, 0.3)'
                }}>
                  {recognitionError}
                </div>
              )}
            </div>
          )}
          
          <div style={{ 
            position: 'absolute',
            bottom: '-70px',
            right: '0px',
            transform: 'translateX(-50%)',
            display: 'flex',
            gap: '20px',
            alignItems: 'center'
          }}>
            <Button 
              onClick={switchToAnswerMode}
              style={{ 
                background: currentMode === 'answer' 
                  ? (isLightTheme ? 'rgba(0, 123, 255, 0.2)' : 'rgba(255, 255, 255, 0.2)')
                  : 'transparent', 
                border: currentMode === 'answer' 
                  ? (isLightTheme ? '2px solid rgba(0, 123, 255, 0.5)' : '2px solid rgba(255, 255, 255, 0.5)')
                  : 'none', 
                padding: '8px',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                width: '60px',
                height: '60px',
                borderRadius: '8px',
                transition: 'all 0.3s ease'
              }}
            >
              <img 
                src={answerIconState === 'answer-icon.svg' ? answerIcon : answerModel}
                alt="回答模式"
                style={{ width: '60px', height: '60px' }}
              />
            </Button>
            <Button 
              onClick={switchToChatMode}
              style={{ 
                background: currentMode === 'chat' 
                  ? (isLightTheme ? 'rgba(40, 167, 69, 0.2)' : 'rgba(255, 255, 255, 0.2)')
                  : 'transparent', 
                border: currentMode === 'chat' 
                  ? (isLightTheme ? '2px solid rgba(40, 167, 69, 0.5)' : '2px solid rgba(255, 255, 255, 0.5)')
                  : 'none', 
                padding: '8px',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                width: '60px',
                height: '60px',
                borderRadius: '8px',
                transition: 'all 0.3s ease'
              }}
            >
              <img 
                src={currentMode === 'chat' ? chatModelActive : chatModel}
                alt="聊天模式"
                style={{ width: '60px', height: '60px' }}
              />
            </Button>
          </div>
        </div>
      </div>
      <div style={footerStyle}></div>
    </div>
  );
};

export default IndexTow;
